package ysq.xyg.web.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import ysq.xyg.base.model.dto.ReturnEntity;
import ysq.xyg.base.service.impl.BaseServiceImpl;
import ysq.xyg.base.util.BaseConstant;
import ysq.xyg.base.util.BaseUtil;
import ysq.xyg.base.util.JwtTokenUtils;
import ysq.xyg.base.util.MD5Util;
import ysq.xyg.sys.model.po.SysDictContent;
import ysq.xyg.sys.model.po.SysUser;
import ysq.xyg.web.dao.WebMemberDao;
import ysq.xyg.web.model.po.WebCheckCode;
import ysq.xyg.web.model.po.WebMember;
import ysq.xyg.web.model.vo.WebMemberVo;
import ysq.xyg.web.service.WebCheckCodeService;
import ysq.xyg.web.service.WebMemberService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 业务模块-会员service实现
 *
 * @author shengQiang yu
 * @date 2019-4-26 13:51:56
 */
@Service("webMemberService")
public class WebMemberServiceImpl extends BaseServiceImpl<WebMember> implements WebMemberService {

    @Autowired
    private WebCheckCodeService webCheckCodeService;
    @Autowired
    private WebMemberDao webMemberDao;
    @Autowired
    public void setBaseDao(WebMemberDao webMemberDao) {
        this.baseDao = webMemberDao;
    }

    /**
     * 分页查询
     *
     * @param webMemberVo 对象
     * @param pageSize    展示数量
     * @param pageNum     当前页面
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-4-26 13:51:56
     */
    public ReturnEntity page(WebMemberVo webMemberVo, int pageSize, int pageNum) {
        if (StrUtil.isNotEmpty(webMemberVo.getNickName())) {
            webMemberVo.setNickName(BaseUtil.encodeBase64String(webMemberVo.getNickName()));
        }
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" update_time desc");
        List<WebMember> list = acceptList(webMemberVo);
        for (WebMember webMember : list) {
            if (StrUtil.isNotEmpty(webMember.getNickName())) {
                webMember.setNickName(BaseUtil.decodeBase64(webMember.getNickName()));
            }
        }
        PageInfo<WebMember> page = new PageInfo<WebMember>(list);
        return new ReturnEntity(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 修改
     *
     * @param webMemberVo 对象
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-4-26 13:51:56
     */
    public ReturnEntity addOrUpdate(WebMemberVo webMemberVo, SysUser currentUser) {
        boolean isUpate = true;
        WebMember webMember;
        if (StrUtil.isEmpty(webMemberVo.getId())) {
            webMember = new WebMember(currentUser);
            isUpate = false;
        } else {
            webMember = selectByPrimaryKey(webMemberVo.getId());
            if (ObjectUtil.isNull(webMember)) {
                return new ReturnEntity(BaseConstant.FAIL, BaseConstant.DO_FAIL);
            }
            webMember.setUpdateTime(new Date());
            webMember.setUpdateUser(currentUser.getId());
        }
        webMember.setCardNo(webMemberVo.getCardNo());
        webMember.setOpenid(webMemberVo.getOpenid());
        webMember.setNickName(webMemberVo.getNickName());
        webMember.setHeadImage(webMemberVo.getHeadImage());
        webMember.setPhone(webMemberVo.getPhone());
        webMember.setName(webMemberVo.getName());
        webMember.setMoney(webMemberVo.getMoney());
        webMember.setUnionid(webMemberVo.getUnionid());
        webMember.setOneCardNo(webMemberVo.getOneCardNo());
        webMember.setTwoCardNo(webMemberVo.getTwoCardNo());
        webMember.setAreaCardNo(webMemberVo.getAreaCardNo());
        webMember.setGrade(webMemberVo.getGrade());
        webMember.setScore(webMemberVo.getScore());
        int num = 0;
        if (isUpate) {
            num = updateByPrimaryKey(webMember);
        } else {
            num = insert(webMember);
        }
        if (num <= 0) {
            return new ReturnEntity(BaseConstant.FAIL, BaseConstant.DO_FAIL);
        }
        return new ReturnEntity();
    }

    /**
     * 删除
     *
     * @param id          主键id
     * @param currentUser 当前用户
     * @return ReturnEntity 对象
     * @author shengQiang yu
     * @date 2019-4-26 13:51:56
     */
    public ReturnEntity delete(String id, SysUser currentUser) {
        WebMember webMember = selectByPrimaryKey(id);
        if (webMember != null) {
            webMember.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_DELETE);
            webMember.setUpdateTime(new Date());
            webMember.setUpdateUser(currentUser.getId());
            int num = updateByPrimaryKey(webMember);
            if (num > 0) {
                return new ReturnEntity();
            }
        }
        return new ReturnEntity(BaseConstant.FAIL, BaseConstant.DO_FAIL);
    }

    /**
     * 获取集合
     *
     * @param webMemberVo 对象
     * @return List<BaseDict> BaseDict集合
     * @author shengQiang yu
     * @date 2019-4-26 13:51:56
     */
    public List<WebMember> acceptList(WebMemberVo webMemberVo) {
        Example example = new Example(WebMember.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotEmpty(webMemberVo.getRemoveTag())) {
            criteria.andEqualTo("removeTag", webMemberVo.getRemoveTag());
        }
        if (StringUtil.isNotEmpty(webMemberVo.getOpenid())) {
            criteria.andEqualTo("openid", webMemberVo.getOpenid());
        }
        if (StringUtil.isNotEmpty(webMemberVo.getGrade())) {
            criteria.andEqualTo("grade", webMemberVo.getGrade());
        }
        if (StringUtil.isNotEmpty(webMemberVo.getAccountId())) {
            criteria.andEqualTo("accountId", webMemberVo.getAccountId());
        }
        if (StringUtil.isNotEmpty(webMemberVo.getCardNo())) {
            criteria.andLike("cardNo", "%" + webMemberVo.getCardNo() + "%");
        }
        if (StringUtil.isNotEmpty(webMemberVo.getNickName())) {
            criteria.andLike("nickName", "%" + webMemberVo.getNickName() + "%");
        }
        if (StringUtil.isNotEmpty(webMemberVo.getName())) {
            criteria.andLike("name", "%" + webMemberVo.getName() + "%");
        }
        if (StringUtil.isNotEmpty(webMemberVo.getPhone())) {
            criteria.andLike("phone", "%" + webMemberVo.getPhone() + "%");
        }
        if (StringUtil.isNotEmpty(webMemberVo.getOneCardNo())) {
            criteria.andEqualTo("oneCardNo", webMemberVo.getOneCardNo());
        }
        if (StringUtil.isNotEmpty(webMemberVo.getTwoCardNo())) {
            criteria.andEqualTo("twoCardNo", webMemberVo.getTwoCardNo());
        }
        if (StringUtil.isNotEmpty(webMemberVo.getAreaCardNo())) {
            criteria.andEqualTo("areaCardNo", webMemberVo.getAreaCardNo());
        }
        example.setOrderByClause(" update_time desc");
        return webMemberDao.selectByExample(example);
    }

    /**
     * 获取会员数量
     *
     * @param webMemberVo 对象
     * @return
     * @author shengQiang yu
     * @date 2019-04-27 9:01
     */
    public int selectCountNum(WebMemberVo webMemberVo) {
        return webMemberDao.selectCountNum(webMemberVo);
    }


    /**
     * 根据openid获取会员信息
     *
     * @param openid 信息
     * @return
     * @author shengQiang yu
     * @date 2019-04-27 9:01
     */
    public WebMember selectEntityByOpenid(String openid) {
        List<WebMember> list = acceptList(new WebMemberVo("", openid, ""));
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 根据unionid获取会员信息
     *
     * @param unionid 信息
     * @return
     * @author shengQiang yu
     * @date 2019-04-27 9:01
     */
    public WebMember selectEntityByUnionId(String unionid) {
        List<WebMember> list = acceptList(new WebMemberVo("", "", unionid));
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 根据cardNo获取会员信息
     *
     * @param cardNo 信息
     * @return
     * @author shengQiang yu
     * @date 2019-04-27 9:01
     */
    public WebMember selectEntityByCardNo(String cardNo) {
        List<WebMember> list = acceptList(new WebMemberVo(cardNo, "", ""));
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 获取最大卡号
     *
     * @return
     * @author shengQiang yu
     * @date 2019-04-27 9:01
     */
    public int selectMaxId() {
        return webMemberDao.selectMaxId(new WebMemberVo());
    }

    @Override
    public int selectMemberCount(WebMember memberEntity) {
        return webMemberDao.selectMemberCount(memberEntity);
    }

    @Override
    public ReturnEntity acceptRecoveryPermissionSelect(String code) {
        WebMemberVo webMemberVo = new WebMemberVo();
        webMemberVo.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        List<WebMember> list = acceptList(webMemberVo);
        List<SysDictContent> sysDictContentList = new ArrayList<SysDictContent>();
        for (WebMember entity : list) {
            SysDictContent sysDictContent = new SysDictContent();
            sysDictContent.setId(entity.getId());
            // 转nickName
            if (StringUtils.isNotEmpty(entity.getNickName())) {
                sysDictContent.setName(BaseUtil.decodeBase64(entity.getNickName()));
            }
            sysDictContent.setDictType(code);
            sysDictContent.setValue(entity.getId());
            sysDictContentList.add(sysDictContent);
        }
        return new ReturnEntity(sysDictContentList);
    }

    @Override
    @Transactional(rollbackFor = {Exception.class})
    public ReturnEntity updateScore(String id, String score, String description) {
        WebMember webMember = this.selectByPrimaryKey(id);
        webMember.setScore(webMember.getScore() + Integer.parseInt(score));
        this.updateByPrimaryKey(webMember);
        return new ReturnEntity();
    }

    @Override
    public ReturnEntity registerByPhone(String code, String phone, String password) {
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code) || !Validator.isMobile(phone)) {
            return new ReturnEntity(BaseConstant.FAIL, "传入数据有误");
        }
        ReturnEntity returnEntity = webCheckCodeService.checkCode(phone, code);
        if (returnEntity.getCode() != BaseConstant.SUCCESS) {
            return returnEntity;
        }
        WebCheckCode webCheckCodes = (WebCheckCode) returnEntity.getData();
        // 查看手机号是否已注册
        WebMember webMember = this.getMemberByPhone(phone);
        if (webMember != null) {
            return new ReturnEntity(BaseConstant.FAIL, "手机号已被注册");
        }
        WebMember member = new WebMember();
        int cardNo = this.selectMaxId();
        if (cardNo < BaseConstant.MEMBER_MIN_DEFAULT_ID) {
            cardNo = BaseConstant.MEMBER_MIN_DEFAULT_ID;
        } else {
            cardNo = cardNo + 1;
        }
        member.setId(BaseUtil.uId());
        member.setName("用户" + String.valueOf(cardNo));
        member.setPassword(MD5Util.MD5Encode(password));
        member.setCardNo(String.valueOf(cardNo));
        member.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        member.setCreateTime(new Date());
        member.setMoney(0.0);
        int ids = this.insert(member);
        if (ids <= 0) {
            return new ReturnEntity(BaseConstant.FAIL, "创建用户失败，请联系管理员");
        }
        if (webCheckCodes != null) {
            webCheckCodes.setUseTime(new Date());
            webCheckCodes.setUseStatus(BaseConstant.BASE_USE_STATUS_YSY);
            webCheckCodeService.updateByPrimaryKey(webCheckCodes);
        }
        String token = JwtTokenUtils.createToken(member.getId(), member.getName(), phone, true);
        return new ReturnEntity(token);
    }

    @Override
    public ReturnEntity login(String phone, String password) {
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(password) || !Validator.isMobile(phone)) {
            return new ReturnEntity(BaseConstant.FAIL, "传入数据有误");
        }
        WebMember webMember = getMemberByPhone(phone);
        if (webMember == null) {
            return new ReturnEntity(BaseConstant.FAIL_TWO, "该手机号尚未注册");
        }
        if (!StringUtils.equals(webMember.getPassword(), MD5Util.MD5Encode(password))) {
            return new ReturnEntity(BaseConstant.FAIL_THREE, "密码错误，请重试");
        }
        String token = JwtTokenUtils.createToken(webMember.getId(), webMember.getName(), phone, true);
        return new ReturnEntity(token);
    }

    @Override
    public WebMember getMemberByPhone(String phone) {
        Example example = new Example(WebMember.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("removeTag", BaseConstant.BASE_REMOVE_TAG_NORMAL);
        criteria.andEqualTo("phone", phone);
        List<WebMember> list = webMemberDao.selectByExample(example);
        if (CollUtil.isNotEmpty(list)) {
            // 手机号已经被注册
            return list.get(0);
        }
        return null;
    }

    @Override
    public ReturnEntity acceptGradeTwoSelect(String code) {
        WebMemberVo webMemberVo = new WebMemberVo();
        webMemberVo.setRemoveTag(BaseConstant.BASE_REMOVE_TAG_NORMAL);
        webMemberVo.setGrade("2");
        List<WebMember> list = acceptList(webMemberVo);
        List<SysDictContent> sysDictContentList = new ArrayList<SysDictContent>();
        for (WebMember entity : list) {
            SysDictContent sysDictContent = new SysDictContent();
            sysDictContent.setId(entity.getId());
            sysDictContent.setName(entity.getName());
            sysDictContent.setDictType(code);
            sysDictContent.setValue(entity.getId());
            sysDictContentList.add(sysDictContent);
        }
        return new ReturnEntity(sysDictContentList);
    }
}
